var path = require('path')
var ctrlLocalToken = require('./ctrl_local_token')
var wechat_file = path.join(__dirname, './access_token.txt')

// 读取文件中有没有token，有则返回token
var Promise = require('bluebird')
var request = Promise.promisify(require('request'))

var prefix = 'https://api.weixin.qq.com/cgi-bin/'
var api = {
    accessToken: prefix + 'token?grant_type=client_credential',
    consult: prefix + 'message/custom/send?access_token='
}
// 读取本地accesstoken文件
function readTokenFile() {
    return ctrlLocalToken.readFileAsync(wechat_file)
}
// 保存本地token文件
function saveTokenToFile(data) {
    data = JSON.stringify(data)
    return ctrlLocalToken.writeFileAsync(wechat_file, data)
}

// 校验token是否过期
function isValidAccessToken(data) {
    if (!data || !data.access_token || !data.expires_in) {
        return false
    }
    var access_token = data.access_token
    var expires_in = data.expires_in

    var now = (new Date().getTime())
    if (now < expires_in) {
        //没过期
        return true
    } else {
        console.log('过期了')
        return false
    }
}

// 请求接口获得access_token
function updateAccessToken(config) {
    var appID = config.wechat.appID
    var appSecret = config.wechat.appSecret
    var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret

    return new Promise(function(resolve, reject) {
        request({ url: url, json: true }).then(function(response) {
            // console.log(response.body)
            var data = response.body
            var now = (new Date().getTime())
            // 生成新的过期时间.留20秒网络延迟时间
            var expires_in = now + (data.expires_in - 20) * 1000
            data.expires_in = expires_in
            resolve(data)
        })
    })
}

exports.gettoken = function(config) {
    var p = new Promise(function(resolve, reject) {
        // 读取本地token文件，看下是否存在以及是否过期
        readTokenFile().then((data) => {
            try {
                var tokenfile = JSON.parse(data)
                // 如果token文件里有access_token并且有expires_in
                if (tokenfile.access_token && tokenfile.expires_in) {

                    if (isValidAccessToken(tokenfile)) {
                        //如果没过期保存并返回token
                        saveTokenToFile(tokenfile)
                        resolve(tokenfile)
                    } else {
                        // 如果过期了，重新请求token
                        updateAccessToken(config).then((data) => {
                            saveTokenToFile(data)
                            resolve(data)
                        })
                    }
                }
            } catch (e) {
                // 票圈不合法、错误就更新一下票圈
                updateAccessToken(config).then((data) => {
                    saveTokenToFile(data)
                    resolve(data)
                })
            }

        })
    })
    return p
}